package com.cuit.qx.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cuit.qx.bean.User;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Scott
 * @Date 2018-07-12 14:23
 * @Desc JWT工具类
 **/
public class JwtUtil {

	private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
	private static final String key="cuit";
	/**
	 * 过期时间
	 **/
	private static final long EXPIRATION = 1800L;//单位为秒

	/**
	 * 生成用户token,设置token超时时间
	 */
	public static String createToken(User user) throws NoSuchAlgorithmException {
		//过期时间
		Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
		Map<String, Object> map = new HashMap<>();
		map.put("alg", "HMA256");
		map.put("typ", "JWT");
		String token = JWT.create()
				.withHeader(map)// 添加头部
				//可以将基本信息放到claims中
				.withClaim("id", user.getUserId())//userId
				.withClaim("userName", user.getUsername())//userName
				.withExpiresAt(expireDate) //超时设置,设置过期的日期
				.withIssuedAt(new Date()) //签发时间
				.sign(Algorithm.HMAC256(key)); //SECRET加密
		return token;
	}

	/**
	 * 校验token并解析token
	 */
	public static Map<String, Claim> verifyToken(String token) throws NoSuchAlgorithmException, InvalidKeySpecException {
		DecodedJWT jwt = null;
		try {
			JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
			jwt = verifier.verify(token);
		} catch (Exception e) {
			logger.error(e.getMessage());
			logger.error("token解码异常");
			//解码异常则抛出异常
			return null;
		}
		return jwt.getClaims();
	}






}